/**
 * 
 */
package com.ph.supplier.api.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.bingoohuang.patchca.random.StrUtils;
import com.google.gson.Gson;
import com.ph.base.BaseController;
import com.ph.shopping.common.core.constant.CommonConstants;
import com.ph.shopping.common.core.customenum.ChargeEnum;
import com.ph.shopping.common.core.customenum.MemberEnum;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.customenum.RoleEnum;
import com.ph.shopping.common.core.exception.BizException;
import com.ph.shopping.common.util.com.order.CreateOrderUtil;
import com.ph.shopping.common.util.com.order.OrderBizCode;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.facade.member.dto.BankCardBindInfoDto;
import com.ph.shopping.facade.member.entity.Member;
import com.ph.shopping.facade.member.service.IBankCardBindService;
import com.ph.shopping.facade.member.service.IMemberService;
import com.ph.shopping.facade.merchant.entity.Position;
import com.ph.shopping.facade.merchant.service.IMerchantService;
import com.ph.shopping.facade.merchant.vo.UserBalanceVo;
import com.ph.shopping.facade.permission.vo.SessionRoleVo;
import com.ph.shopping.facade.permission.vo.SessionUserVo;
import com.ph.shopping.facade.supplier.entity.Supplier;
import com.ph.shopping.facade.supplier.entity.SupplierChargeRecord;
import com.ph.shopping.facade.supplier.entity.SupplierDrawcashRecord;
import com.ph.shopping.facade.supplier.entity.SupplierImage;
import com.ph.shopping.facade.supplier.service.ISupplierService;
import com.ph.shopping.facade.supplier.vo.SupplierBalanceRecordVo;
import com.ph.shopping.facade.supplier.vo.SupplierVo;

/**
 * @项目：phshopping-api-platform
 *
 * @描述：供应商Controller
 *
 * @作者： liuy
 *
 * @创建时间：2017年3月15日
 *
 * @Copyright @2017 by liuy
 */
@Controller
@RequestMapping("api/supplier")
public class SupplierController extends BaseController{

	@Reference(version="1.0.0")
	private ISupplierService iSupplierService;
	
	//会员接口，调用通过手机号获取会员信息 
	@Reference(version="1.0.0")
	private IMemberService iMemberService;

	//商户接口，调用获取省市区的方法
	@Reference(version="1.0.0")
	private IMerchantService iMerchantService;

    //银行卡绑定接口，用于获取银行卡信息
    @Reference(version = "1.0.0")
    private IBankCardBindService iBankCardBindService;
    
	/**
	 * 跳转供应商列表页面
	 * @return
	 */
	@RequestMapping(value="/listPage",method=RequestMethod.GET)
	public String listSupplierPage(){
		return "/supplier/list";
	}

	/**
	 * 跳转供应商新增页面
	 * @return
	 */
	@RequestMapping(value="/addPage",method=RequestMethod.GET)
	public String addSupplierPage(){
		return "/supplier/add";
	}
	
	/**
	 * 
	 *  跳转供应商修改页面（根据id获取供应商信息）
	 * @param 
	 * @return
	 */
	@RequestMapping(value="/updatePage",method=RequestMethod.GET)
	public Object updateSupplierPage(@ModelAttribute SupplierVo supplierVo){

		ModelAndView mv=new ModelAndView("/supplier/update");
		try {
			SupplierVo supplierDetailVo = iSupplierService.getSupplierVoDetail(supplierVo);
			if(supplierDetailVo.getPositionId()==null||"".equals(supplierDetailVo.getPositionId())){
				supplierDetailVo.setProvinceId(Long.valueOf("-1"));
				supplierDetailVo.setCityId(Long.valueOf("-1"));
				supplierDetailVo.setCountyId(Long.valueOf("-1"));
			}
			mv.addObject("supplier", supplierDetailVo);
			return mv;
		} catch (BizException e) {
			mv.addObject("supplier", supplierVo);
			logger.error("获取供应商信息异常:", e.getMessage());
			return mv;
		}
		
	}

	/**
	 * 跳转供应商详情页面
	 * @return
	 */
	@RequestMapping(value="/detailPage",method=RequestMethod.GET)
	public Object detailSupplierPage(@ModelAttribute SupplierVo supplierVo){
		
		//获取session，如果登陆角色类型是供应商，设置供应商Id为用户Id去查询供应商详情
		SessionUserVo sessionUserVo = getLoginUser();
		if(sessionUserVo!=null&&sessionUserVo.getId()!=null&&sessionUserVo.getSessionRoleVo()!=null
				&&sessionUserVo.getSessionRoleVo().get(0)!=null){
			SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
			RoleEnum roleEnum = RoleEnum.getRoleEnumByCode(sessionRoleVo.getRoleCode());
			if(roleEnum.equals(RoleEnum.SUPPLIER)){
				supplierVo.setId(sessionUserVo.getId());
			}
		}
		
		try {
			ModelAndView mv=new ModelAndView("/supplier/detail");
			SupplierVo supplierDetailVo = iSupplierService.getSupplierVoDetail(supplierVo);
			mv.addObject("supplier", supplierDetailVo);
			return mv;
		} catch (BizException e) {
			e.printStackTrace();
			logger.error("获取供应商信息异常:", e.getMessage());
			return "";
		}
	}
	
	/**
	 * 跳转待审核供应商页面
	 * @return
	 */
	@RequestMapping(value="/listExaminePage",method=RequestMethod.GET)
	public String listExamineSupplierPage(){
		return "/supplier/examinelist";
	}
	
	/**
	 * 分页获取供应商列表(包括供应商列表和待审核供应商列表)
     * @param pageIndex 当前页码
     * @param pageSize 每页条数
     * @param supplierVo 查询条件
	 * @return
	 */
	@RequestMapping(value="/pagelist",method= RequestMethod.GET)
	@ResponseBody
	public Object getSupplierVoListByPage(@ModelAttribute PageBean page,@ModelAttribute SupplierVo supplierVo) {

		//获取session，通过Session获取用户Id
		SessionUserVo sessionUserVo = getLoginUser();
		
		if(sessionUserVo!=null&&sessionUserVo.getId()!=null
				&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
			
			//查询供应商的角色可能有两个  平台和市级代理
			//平台查询所有供应商，市级代理查询自己添加的供应商和全国供应商
			SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
			RoleEnum roleEnum = RoleEnum.getRoleEnumByCode(sessionRoleVo.getRoleCode());

			if(roleEnum.equals(RoleEnum.CITY_AGENT)){
				supplierVo.setCreateId(sessionUserVo.getId());				//自己的Id
				supplierVo.setSupplierType(CommonConstants.NOT_ADMIN_ROLE);	//非管理员角色查询供应商 类型
			}
		
		}
		Result result = iSupplierService.getSupplierVoPageList(page,supplierVo);
		return result;
	}

	/**
	 * 获取供应商列表（不分页）
     * @param supplierVo 查询条件
	 * @return
	 */
	@RequestMapping(value="/list",method=RequestMethod.GET)
	@ResponseBody
	public Object getSupplierVoList(@ModelAttribute Supplier supplier){
		return getResult(ResultEnum.SUCCESS,iSupplierService.getSupplierVoList(supplier));
	}

	/**
	 * 分页查询余额记录列表
	 * @param page
	 * @return result
	 */
	@RequestMapping(value="/balance",method=RequestMethod.GET)
	@ResponseBody
	public Object getBalanceSupplierVoListByPage(@ModelAttribute PageBean page,SupplierBalanceRecordVo supplierBalanceR){
		Result result = iSupplierService.getBalanceSupplierVoPageList( page,supplierBalanceR);
		return result;
	}
	
	/**
	 * 新增供应商
	 * @param supplier
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.POST)
	@ResponseBody
	public Object addSupplier(@ModelAttribute Supplier supplier, HttpServletRequest request){
		logger.info("供应商新增，传入参数：" + supplier + "" + request );
		
		String businesslicenseImage = request.getParameter("businesslicenseImage");
		String idCardImage1 =  request.getParameter("idCardImage1");
		String idCardImage2 =  request.getParameter("idCardImage2");
		
		List<SupplierImage> imageList = new ArrayList<SupplierImage>();

		if(!businesslicenseImage.equals("")){
			SupplierImage supplierImage1 = new SupplierImage();
			supplierImage1.setType(CommonConstants.BUSINESS_IMAGE_TYPE);
			supplierImage1.setSort(CommonConstants.BUSINESS_IMAGE_SORT);//营业执照
			supplierImage1.setUrl(businesslicenseImage);

			imageList.add(supplierImage1);
		}
		if(!idCardImage1.equals("")){
			SupplierImage supplierImage2 = new SupplierImage();
			supplierImage2.setType(CommonConstants.IDCARD_IMAGE_TYPE);//身份证正面
			supplierImage2.setSort(CommonConstants.IDCARD1_IMAGE_SORT);//身份证正面
			supplierImage2.setUrl(idCardImage1);
			imageList.add(supplierImage2);
		}
		if(!idCardImage2.equals("")){
			SupplierImage supplierImage3 = new SupplierImage();
			supplierImage3.setType(CommonConstants.IDCARD_IMAGE_TYPE);//身份证反面
			supplierImage3.setSort(CommonConstants.IDCARD2_IMAGE_SORT);//身份证反面
			supplierImage3.setUrl(idCardImage2);
			imageList.add(supplierImage3);
		}
		
		//获取session
		SessionUserVo sessionUserVo = getLoginUser();
		
		if(sessionUserVo!=null&&sessionUserVo.getId()!=null
				&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
			
			//1.设置供应商类型
			SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
			if(sessionRoleVo.getRoleCode()!=null&&!"".equals(sessionRoleVo.getRoleCode())){
				RoleEnum roleEnum = RoleEnum.getRoleEnumByCode(sessionRoleVo.getRoleCode());
				if(roleEnum.equals(RoleEnum.CITY_AGENT)){
					supplier.setSupplierType(CommonConstants.SUPPLIER_TYPE_LOCAL);//本地
				}else{
					supplier.setSupplierType(CommonConstants.SUPPLIER_TYPE_TOTAL);//全国
				}
			}else{//如果没有session，默认为全国
				supplier.setSupplierType(CommonConstants.SUPPLIER_TYPE_TOTAL);//全国
			}
			
			//2.设置创建人（创建人的Id为登录IDd，有可能是平台和市级代理商两种类型）、 更新人
			supplier.setCreateId(sessionUserVo.getId());
			supplier.setUpdateId(sessionUserVo.getId());
			
		}else{//如果没有session，默认为全国
			supplier.setSupplierType(CommonConstants.SUPPLIER_TYPE_TOTAL);//全国
		}

		supplier.setCreateTime(new Date());
		supplier.setUpdateTime(new Date());
		supplier.setStatus(CommonConstants.CHECK_PENDING);//新增时状态为0，待审核
		
		if(StrUtils.isNotEmpty(supplier.getCountyId())){
			//将区域最后一级（区Id）设置为positionId
			supplier.setPositionId(Long.valueOf(supplier.getCountyId()));
			//根据positionId获取区域对象，对省市区Id进行赋值
			Position position = iMerchantService.getPositionById(supplier.getCountyId());
			if(position!=null){
				supplier.setProvinceId(position.getProvinceId());
				supplier.setCityId(position.getCityId());
				supplier.setCountyId(position.getCountyId());
			}
		}
		
		// 3.后台数据验证
		Gson gson = new Gson();
		List<String> errorList = supplier.validateForm();
		if (errorList != null) {
			logger.info(
					"信息检索表[com.ph.shopping.facade.supplier.entity.Supplier]实体验证错误：错误信息如下" + gson.toJson(errorList));
			return getResult(ResultEnum.ENTITY_CHECK_SUPPLIER_EXCEPTION);
		}
		for (SupplierImage supplierImage : imageList) {
			List<String> errorList1 = supplierImage.validateForm();
			if (errorList1 != null) {
				logger.info("信息检索表[com.ph.shopping.facade.supplier.entity.SupplierImage]实体验证错误：错误信息如下"
						+ gson.toJson(errorList1));
				return getResult(ResultEnum.ENTITY_CHECK_SUPPLIER_EXCEPTION);
			}
		}
		
		Result result = getResult(ResultEnum.SUCCESS);
		
		// 4.开始新增
		try {
			logger.debug("供应商新增数据：");
			logger.debug("supplier: " + new ObjectMapper().writeValueAsString(supplier));
			logger.debug("imageList: " + new ObjectMapper().writeValueAsString(imageList));
			result =this.iSupplierService.addSupplier(supplier, imageList);
		} catch (BizException e) {
			e.printStackTrace();
			logger.error("供应商新增数据异常:", e.getMessage());
			return getResult(ResultEnum.ADD_SUPPLIER_EXCEPTION);
		} catch(Exception e1){
			e1.printStackTrace();
			logger.error("供应商新增数据异常:", e1.getMessage());
			return getResult(ResultEnum.ADD_SUPPLIER_EXCEPTION);
		}
		logger.info("供应商新增成功");
		return result;
		
	}
	
	/**
	 * 修改供应商
	 * @param supplier
	 * @return
	 */
	@RequestMapping(value="/update",method=RequestMethod.POST)
	@ResponseBody
	public Object updateSupplier(@ModelAttribute Supplier supplier, HttpServletRequest request) {
		logger.info("供应商修改，传入参数：" + supplier + "" + request );
		
		String businesslicenseImage = request.getParameter("businesslicenseImage");
		String idCardImage1 =  request.getParameter("idCardImage1");
		String idCardImage2 =  request.getParameter("idCardImage2");
		
		List<SupplierImage> imageList = new ArrayList<SupplierImage>();

		if(!businesslicenseImage.equals("")){
			SupplierImage supplierImage1 = new SupplierImage();
			supplierImage1.setType(CommonConstants.BUSINESS_IMAGE_TYPE);
			supplierImage1.setSort(CommonConstants.BUSINESS_IMAGE_SORT);//营业执照
			supplierImage1.setUrl(businesslicenseImage);

			imageList.add(supplierImage1);
		}
		if(!idCardImage1.equals("")){
			SupplierImage supplierImage2 = new SupplierImage();
			supplierImage2.setType(CommonConstants.IDCARD_IMAGE_TYPE);//身份证正面
			supplierImage2.setSort(CommonConstants.IDCARD1_IMAGE_SORT);//身份证正面
			supplierImage2.setUrl(idCardImage1);
			imageList.add(supplierImage2);
		}
		if(!idCardImage2.equals("")){
			SupplierImage supplierImage3 = new SupplierImage();
			supplierImage3.setType(CommonConstants.IDCARD_IMAGE_TYPE);//身份证反面
			supplierImage3.setSort(CommonConstants.IDCARD2_IMAGE_SORT);//身份证反面
			supplierImage3.setUrl(idCardImage2);
			imageList.add(supplierImage3);
		}
		
		//获取session
		SessionUserVo sessionUserVo = getLoginUser();
		
		if(sessionUserVo!=null&&sessionUserVo.getId()!=null
				&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
			//1.设置供应商类型
			SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
			if(sessionRoleVo.getRoleCode()!=null&&!"".equals(sessionRoleVo.getRoleCode())){
				RoleEnum roleEnum = RoleEnum.getRoleEnumByCode(sessionRoleVo.getRoleCode());
				if(roleEnum.equals(RoleEnum.CITY_AGENT)){
					supplier.setSupplierType(CommonConstants.SUPPLIER_TYPE_LOCAL);//本地
				}else{
					supplier.setSupplierType(CommonConstants.SUPPLIER_TYPE_TOTAL);//全国
				}
			}
			
			//2.设置创建人、 更新人
			supplier.setUpdateId(sessionUserVo.getId());
		}
		
		if(StrUtils.isNotEmpty(supplier.getPositionId())){
			//根据positionId获取区域对象，对省市区Id进行赋值
			Position position = iMerchantService.getPositionById(supplier.getPositionId());
			if(position!=null){
				supplier.setProvinceId(position.getProvinceId());
				supplier.setCityId(position.getCityId());
				supplier.setCountyId(position.getCountyId());
			}
		}
		
		supplier.setUpdateTime(new Date());
		
		// 3.后台数据验证开始
		Gson gson = new Gson();
		List<String> errorList = supplier.validateForm();
		if (errorList != null) {
			logger.info(
					"信息检索表[com.ph.shopping.facade.supplier.entity.Supplier]实体验证错误：错误信息如下" + gson.toJson(errorList));
			return getResult(ResultEnum.ENTITY_CHECK_SUPPLIER_EXCEPTION);
		}
		for (SupplierImage supplierImage : imageList) {
			List<String> errorList1 = supplierImage.validateForm();
			if (errorList1 != null) {
				logger.info("信息检索表[com.ph.shopping.facade.supplier.entity.SupplierImage]实体验证错误：错误信息如下"
						+ gson.toJson(errorList1));
				return getResult(ResultEnum.ENTITY_CHECK_SUPPLIER_EXCEPTION);
			}
			supplierImage.setCreateTime(new Date());
			supplierImage.setSupplierId(supplier.getId());
		}

		Result result = getResult(ResultEnum.SUCCESS);
		
		// 4..开始修改
		try {
			logger.debug("供应商修改数据：");
			logger.debug("supplier: " + supplier);
			logger.debug("imageList: " + imageList);

			result = this.iSupplierService.updateSupplier(supplier, imageList);
		} catch (BizException e) {
			e.printStackTrace();
			logger.error("供应商修改数据异常:", e.getMessage());
			return getResult(ResultEnum.UPDATE_SUPPLIER_EXCEPTION);
		}
		logger.info("供应商修改成功");
		return result;
	}

	/**
	 * 删除
	 * @param supplier
	 * @return
	 */
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	@ResponseBody
	public Object batchDeleteSupplier(String supplierIds) {
		try {
			String[] sIds = supplierIds.split(",");
			Long[] str2 = new Long[sIds.length];
	        for (int i = 0; i < sIds.length; i++) {
	            str2[i] = Long.valueOf(sIds[i]);
	        }
			List<Long> list = new ArrayList<Long>();
			Collections.addAll(list, str2);
			this.iSupplierService.batchDeleteSupplier(list);
		} catch (BizException e) { 
			e.printStackTrace();
			logger.error("删除供应商异常:"+ e.getMessage());
			return getResult(ResultEnum.DELETE_SUPPLIER_EXCEPTION);
		}

		return getResult(ResultEnum.SUCCESS);
	}

	/**
	 * 冻结、解冻供应商操作
	 * @param supplier
	 * @return
	 */
	@RequestMapping(value="/congealSupplier",method=RequestMethod.POST)
	@ResponseBody
	public Object congealSupplier(@ModelAttribute Supplier supplier, HttpServletRequest request) {

		Result result = getResult(ResultEnum.SUCCESS);
		
		try {
			//获取session
			SessionUserVo sessionUserVo = getLoginUser();
			//设置 更新人
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				supplier.setUpdateId(sessionUserVo.getId());
			}
			//设置 更新时间
			supplier.setUpdateTime(new Date());

	    	if(supplier.getStatus()==CommonConstants.SUPPLER_ISABLE_NO){
				//1.如果是冻结，需要清空冻结用户的登录session
	    		sessionUserVo.getId();
				request.getSession().removeAttribute(supplier.getPersonTel());
	    	}
			
			//2.修改供应商表状态为冻结：3，解冻 ：1
	    	 result = this.iSupplierService.congealSupplier(supplier);
		} catch (BizException e) {
			e.printStackTrace();
			if(supplier.getStatus()==CommonConstants.SUPPLER_ISABLE_NO){
				logger.error("供应商冻结异常:"+ e.getMessage());
				return getResult(ResultEnum.CONGEALNO_SUPPLIER_EXCEPTION);
			}else{
				logger.error("供应商解冻异常:"+ e.getMessage());
				return getResult(ResultEnum.CONGEALYES_SUPPLIER_EXCEPTION);
			}
		}
		return result;
	}

	/**
	 * 审核供应商操作
	 * @param supplier
	 * @return
	 */
	@RequestMapping(value="/examineSupplier",method=RequestMethod.POST)
	@ResponseBody
	public Object examineSupplier(@ModelAttribute Supplier supplier){

		Result result = getResult(ResultEnum.SUCCESS);
		try {
			//获取session
			SessionUserVo sessionUserVo = getLoginUser();
			//设置 更新人
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				supplier.setUpdateId(sessionUserVo.getId());
			}
			//设置 更新时间
			supplier.setUpdateTime(new Date());
			
			//修改供应商表状态为正常：1或者不通过：2
			result = this.iSupplierService.examineSupplier(supplier);
		} catch (BizException e) {
			e.printStackTrace();
			if(supplier.getStatus()==CommonConstants.SUPPLER_EXAMINE_YES){
				logger.error("供应商审核通过异常:"+ e.getMessage());
				return getResult(ResultEnum.EXAMINEYES_SUPPLIER_EXCEPTION);
			}else{
				logger.error("供应商审核不通过异常:"+ e.getMessage());
				return getResult(ResultEnum.EXAMINENO_SUPPLIER_EXCEPTION);
			}
		}
		return result;
	}
	
	/**
	 * 根据推广师电话自动获取推广师姓名
	 * @param supplier
	 * @return
	 */
	@RequestMapping(value="/getPromoterNameByTel",method=RequestMethod.GET)
	@ResponseBody
	public Object getPromoterNameByTel(@ModelAttribute Supplier supplier){
		Member member = (Member) iMemberService.getMemberInfoByMobile(supplier.getPromoterTel()).getData();
		String promoterName = "";
		//当IsMarketing为1时，表示是推广师。否则页面返回空
		if(member!=null && !"null".equals(member)&&member.getMemberName()!=null && member.getIsMarketing()==Byte.valueOf(CommonConstants.IS_PROMOTER)){
			promoterName = member.getMemberName();
			return getResult(ResultEnum.SUCCESS,promoterName);
		}else{
			logger.error("根据推广师电话自动获取推广师姓名,调用的接口未抛出异常。");
			return getResult(ResultEnum.PROMOTER_NON_EXISTENT);
		}
	}
	
	//--------------------------充值和提现初始版（供应商可能没有）--------------------------------------------//

	/**
	 * 跳转到充值页面
	 * @author 刘颖
	 * @return
	 */
	@RequestMapping(value = "/chargeSupplierPage", method = RequestMethod.GET)
	public Object chargeSupplierPage() {

		//获取session
		SessionUserVo sessionUserVo = getLoginUser();
		
		ModelAndView mv=new ModelAndView("/supplier/suppliereSupplierPage");
		UserBalanceVo userBalanceVo = new UserBalanceVo();
		userBalanceVo.setManageId(sessionUserVo.getId());
		
		//1.通过代理商Id获取银行卡信息
		Result result = iBankCardBindService.getBankCardInfo(sessionUserVo.getId(), MemberEnum.PLATFORM_BANK.getCode());
		BankCardBindInfoDto bankCardBindInfoDto =  (BankCardBindInfoDto) result.getData();
		if(bankCardBindInfoDto!=null){
			userBalanceVo.setBankId(bankCardBindInfoDto.getBankId());//绑定id
			userBalanceVo.setBankName(bankCardBindInfoDto.getBankName());//银行名称
			userBalanceVo.setBindPhone(bankCardBindInfoDto.getBindPhone());//绑定手机号
			userBalanceVo.setCardNum(bankCardBindInfoDto.getCardNum());//卡号
			userBalanceVo.setOwnName(bankCardBindInfoDto.getOwnName());//银行卡所属人
		}

		mv.addObject("userBalanceVo", userBalanceVo);
		return mv;
	}

	/**
	 * 跳转到提现页面
	 * @author 刘颖
	 * @return
	 */
	@RequestMapping(value = "/drawcashSupplierPage", method = RequestMethod.GET)
	public Object drawcashSupplierPage() {

		//获取session
		SessionUserVo sessionUserVo = getLoginUser();
		
		ModelAndView mv=new ModelAndView("/supplier/drawcashSupplierPage");
		UserBalanceVo userBalanceVo = new UserBalanceVo();
		userBalanceVo.setManageId(sessionUserVo.getId());
		
		//1.通过代理商Id获取银行卡信息
		Result result = iBankCardBindService.getBankCardInfo(sessionUserVo.getId(), MemberEnum.PLATFORM_BANK.getCode());
		BankCardBindInfoDto bankCardBindInfoDto =  (BankCardBindInfoDto) result.getData();
		if(bankCardBindInfoDto!=null){
			userBalanceVo.setBankId(bankCardBindInfoDto.getBankId());//绑定id
			userBalanceVo.setBankName(bankCardBindInfoDto.getBankName());//银行名称
			userBalanceVo.setBindPhone(bankCardBindInfoDto.getBindPhone());//绑定手机号
			userBalanceVo.setCardNum(bankCardBindInfoDto.getCardNum());//卡号
			userBalanceVo.setOwnName(bankCardBindInfoDto.getOwnName());//银行卡所属人
		}

		mv.addObject("userBalanceVo", userBalanceVo);
		return mv;
	}


	/**
	 * 充值的上一步，创建订单，返回订单号
	 * @param userBalanceVo
	 * @return
	 * @author 刘颖
	 */
	@ResponseBody
	@RequestMapping(value="/chargeSupplierCreateOrder",method=RequestMethod.POST)
	public Object chargeSupplierCreateOrder(@ModelAttribute("userBalanceVo") UserBalanceVo userBalanceVo) throws Exception  {
		//1.生成订单号，用于充值记录
		String orderNum = CreateOrderUtil.createOrderCode(OrderBizCode.AGENT_CAHRGE);
		//2.生成充值记录
		SupplierChargeRecord supplierChargeRecord = new SupplierChargeRecord();
		supplierChargeRecord.setSupplierId(userBalanceVo.getManageId());
		supplierChargeRecord.setScore(userBalanceVo.getChargeMoney().multiply(new BigDecimal(10000)));
		supplierChargeRecord.setOrderNum(orderNum);
		supplierChargeRecord.setChargeType(ChargeEnum.CHARGE_TYPE.getCode());
		supplierChargeRecord.setCreater(userBalanceVo.getManageId());
		supplierChargeRecord.setCreateTime(new Date());
		iSupplierService.addSupplierChargeRecord(supplierChargeRecord);
		//返回订单号
		return getResult(ResultEnum.SUCCESS,orderNum);
	}


	/**
	 * 提现
	 * @param userBalanceVo
	 * @return
	 * @author 刘颖
	 */
	@ResponseBody
	@RequestMapping(value="/drawcashSupplier",method=RequestMethod.POST)
	public Object drawcashSupplier(@ModelAttribute("userBalanceVo") UserBalanceVo userBalanceVo) throws Exception  {
		//写提现表
		SupplierDrawcashRecord supplierDrawcashRecord = new SupplierDrawcashRecord();
		supplierDrawcashRecord.setSupplierId(userBalanceVo.getManageId());
		supplierDrawcashRecord.setScore(userBalanceVo.getDrawcashMoney().divide(new BigDecimal(10000)));
		supplierDrawcashRecord.setCreateDate(new Date());
		supplierDrawcashRecord.setBankName(userBalanceVo.getBankName());
		supplierDrawcashRecord.setDrawcashIp("");//这里要设置Ip
		supplierDrawcashRecord.setReceiver(userBalanceVo.getOwnName());
		supplierDrawcashRecord.setBankNo(userBalanceVo.getCardNum());
		supplierDrawcashRecord.setCreater(userBalanceVo.getManageId());
		supplierDrawcashRecord.setCreateTime(new Date());
		iSupplierService.addSupplierDrawcashRecord(supplierDrawcashRecord);
		return getResult(ResultEnum.SUCCESS);
	}

}
